import axios from 'axios'
import { useAuthStore } from '@/store/auth'

const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  async config => {
    const authStore = useAuthStore()
	
    // 检查Token是否即将过期，如果是则刷新Token
    if (authStore.isTokenExpiringSoon()) {
      await authStore.refreshToken()
    }
    
    // 添加Authorization头
    if (authStore.token) {
      config.headers.Authorization = `Bearer ${authStore.token}`
    }
    
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => response.data,     
  async error => {
    const originalRequest = error.config

    
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true

      const authStore = useAuthStore()
      const refreshed = await authStore.refreshToken()

      if (refreshed) {
       
        originalRequest.headers.Authorization = `Bearer ${authStore.token}`
        return api(originalRequest)
      }
    }

    return Promise.reject(error)
  }
)

export default api